package com.fastadmin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fastadmin.mapper.impl.RoleMapper;
import com.fastadmin.mapper.impl.RoleResourceMapper;
import com.fastadmin.pojo.FastParam;
import com.fastadmin.pojo.Role;
import com.fastadmin.pojo.RoleResource;
import com.fastadmin.pojo.User;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.xphsc.easyjdbc.page.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequiredArgsConstructor
@Slf4j
@CacheConfig(cacheNames = "roleResource")
public class RoleController extends BaseController {

    private final RoleMapper roleMapper;
    private final RoleResourceMapper roleResourceMapper;

    @GetMapping("/sys/role/{path}")
    public String index(@PathVariable String path) {
        return "sys/role/" + path;
    }

    @GetMapping("/sys/role/edit")
    public String index(Model model, String ids,String authorities) {
        List<Object> roleIds = Lists.newArrayList();
        List<Role> roles = roleMapper.findByRole_key(authorities);
        for (Role role : roles) {
            roleIds.add(role.getId());
        }
        List<String> resourceIds = roleResourceMapper.findByRoleIds(ids);
        Role role = roleMapper.findById(ids);
        model.addAttribute("role", role);
        model.addAttribute("resourceIds", CollUtil.join(resourceIds, ","));
        return "sys/role/edit";
    }

    @GetMapping("sys/role/data")
    @ResponseBody
    public Object data(FastParam param) {
        PageInfo<Role> pageInfo = roleMapper.findByFastParam(param);
        return datagrid(pageInfo);
    }

    @RequestMapping("sys/role/del")
    @ResponseBody
    public Object del(String ids) {
        int i = roleMapper.deleteByIds(ids);
        return ok();
    }

    @RequestMapping("sys/role/save")
    @ResponseBody

    public Object save(Role role, String resources) {
        ThreadUtil.execAsync(() -> {
            //修改角色表的信息，那么先删除掉库里面所有关于角色id的资源
            if (ObjectUtil.isNotNull(role.getId())) {
                roleResourceMapper.deleteByRoleId(role.getId());
                //然后插入新搞得
                String[] split = StrUtil.split(resources, ",");
                for (String resource_id : split) {
                    RoleResource roleResource = RoleResource.builder().resource_id(Long.valueOf(resource_id)).role_id(role.getId()).build();
                    roleResourceMapper.save(roleResource);
                }
                roleMapper.update(role);
            } else {
                Object save = roleMapper.save(role);
                String[] split = StrUtil.split(resources, ",");
                Long role_id = Long.valueOf(save.toString());
                for (String resource_id : split) {
                    RoleResource roleResource = RoleResource.builder().resource_id(Long.valueOf(resource_id)).role_id(role_id).build();
                    roleResourceMapper.save(roleResource);
                }
            }
        });
        return ok();
    }

    @RequestMapping(value = "/sys/role/tree",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object tree(String role_key) {
        List<Map<String, Object>> resourceByRole = roleResourceMapper.findResourceByRole(role_key);
        resourceByRole.stream().map(map -> {
            if (map.get("parent").toString().equals("0")) {
                map.put("parent", "#");
            }
            map.put("state", ImmutableMap.of("selected", false));

            return map;
        }).collect(Collectors.toList());
        return buildJson(1, "ok", resourceByRole);
    }
}
